package com.example.managemyself.ui.auth;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.managemyself.R;
import com.example.managemyself.util.EmailService;
import com.example.managemyself.data.database.AppDatabase;
import com.example.managemyself.data.model.User;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ForgotPasswordActivity extends AppCompatActivity {

    private TextInputLayout tilEmail, tilUsername, tilVerificationCode, tilNewPassword, tilConfirmPassword;
    private TextInputEditText etEmail, etUsername, etVerificationCode, etNewPassword, etConfirmPassword;
    private Button btnSendEmail, btnVerifyCode, btnResetPassword;
    private ProgressBar progressBar;
    private TextView tvStepStatus;
    
    private EmailService emailService;
    private AppDatabase database;
    private ExecutorService executorService;
    private String verifiedEmail;
    private String verifiedUsername;

    private enum ResetStep {
        EMAIL_INPUT,
        CODE_VERIFICATION,
        PASSWORD_RESET
    }

    private ResetStep currentStep = ResetStep.EMAIL_INPUT;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forgot_password);

        emailService = EmailService.getInstance();
        emailService.setContext(this);
        database = AppDatabase.getInstance(this);
        executorService = Executors.newSingleThreadExecutor();
        
        initViews();
        setupListeners();
        updateUIForCurrentStep();
    }

    private void initViews() {
        tilEmail = findViewById(R.id.tilEmail);
        tilUsername = findViewById(R.id.tilUsername);
        tilVerificationCode = findViewById(R.id.tilVerificationCode);
        tilNewPassword = findViewById(R.id.tilNewPassword);
        tilConfirmPassword = findViewById(R.id.tilConfirmPassword);

        etEmail = findViewById(R.id.etEmail);
        etUsername = findViewById(R.id.etUsername);
        etVerificationCode = findViewById(R.id.etVerificationCode);
        etNewPassword = findViewById(R.id.etNewPassword);
        etConfirmPassword = findViewById(R.id.etConfirmPassword);

        btnSendEmail = findViewById(R.id.btnSendEmail);
        btnVerifyCode = findViewById(R.id.btnVerifyCode);
        btnResetPassword = findViewById(R.id.btnResetPassword);

        progressBar = findViewById(R.id.progressBar);
        tvStepStatus = findViewById(R.id.tvStepStatus);
    }

    private void setupListeners() {
        btnSendEmail.setOnClickListener(v -> sendVerificationEmail());
        btnVerifyCode.setOnClickListener(v -> verifyCode());
        btnResetPassword.setOnClickListener(v -> resetPassword());
    }

    private void updateUIForCurrentStep() {
        // 隐藏所有UI元素
        tilEmail.setVisibility(View.GONE);
        tilUsername.setVisibility(View.GONE);
        tilVerificationCode.setVisibility(View.GONE);
        tilNewPassword.setVisibility(View.GONE);
        tilConfirmPassword.setVisibility(View.GONE);
        
        btnSendEmail.setVisibility(View.GONE);
        btnVerifyCode.setVisibility(View.GONE);
        btnResetPassword.setVisibility(View.GONE);
        
        // 根据当前步骤显示相应UI
        switch (currentStep) {
            case EMAIL_INPUT:
                tvStepStatus.setText("步骤 1/3: 输入您的用户名和注册邮箱");
                tilUsername.setVisibility(View.VISIBLE);
                tilEmail.setVisibility(View.VISIBLE);
                btnSendEmail.setVisibility(View.VISIBLE);
                break;
                
            case CODE_VERIFICATION:
                tvStepStatus.setText("步骤 2/3: 输入您收到的验证码");
                tilUsername.setVisibility(View.VISIBLE);
                tilEmail.setVisibility(View.VISIBLE);
                tilVerificationCode.setVisibility(View.VISIBLE);
                btnVerifyCode.setVisibility(View.VISIBLE);
                
                // 禁用用户名和邮箱输入
                etUsername.setEnabled(false);
                etEmail.setEnabled(false);
                break;
                
            case PASSWORD_RESET:
                tvStepStatus.setText("步骤 3/3: 设置新密码");
                tilNewPassword.setVisibility(View.VISIBLE);
                tilConfirmPassword.setVisibility(View.VISIBLE);
                btnResetPassword.setVisibility(View.VISIBLE);
                break;
        }
    }

    private void sendVerificationEmail() {
        String username = etUsername.getText().toString().trim();
        String email = etEmail.getText().toString().trim();
        
        // 验证输入
        if (username.isEmpty()) {
            etUsername.setError("请输入用户名");
            etUsername.requestFocus();
            return;
        }
        
        if (email.isEmpty()) {
            etEmail.setError("请输入邮箱");
            etEmail.requestFocus();
            return;
        }
        
        if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            etEmail.setError("请输入有效的邮箱地址");
            etEmail.requestFocus();
            return;
        }
        
        // 显示加载状态
        showLoading(true);
        
        // 验证用户名和邮箱是否匹配
        executorService.execute(() -> {
            try {
                User user = database.userDao().getUserByUsernameSync(username);
                
                runOnUiThread(() -> {
                    if (user == null) {
                        showLoading(false);
                        etUsername.setError("用户名不存在");
                        etUsername.requestFocus();
                        return;
                    }
                    
                    if (!email.equals(user.getEmail())) {
                        showLoading(false);
                        etEmail.setError("邮箱与用户名不匹配");
                        etEmail.requestFocus();
                        return;
                    }
                    
                    // 发送验证码邮件
                    emailService.sendVerificationCode(email, username, new EmailService.EmailCallback() {
                        @Override
                        public void onSuccess(String result) {
                            showLoading(false);
                            verifiedEmail = email;
                            verifiedUsername = username;
                            Toast.makeText(ForgotPasswordActivity.this, 
                                "验证码已发送到您的邮箱，请查收", Toast.LENGTH_LONG).show();
                            
                            // 更新UI进入下一步
                            currentStep = ResetStep.CODE_VERIFICATION;
                            updateUIForCurrentStep();
                        }
                        
                        @Override
                        public void onError(String error) {
                            showLoading(false);
                            Toast.makeText(ForgotPasswordActivity.this, 
                                "发送验证码失败: " + error, Toast.LENGTH_LONG).show();
                        }
                    });
                });
                
            } catch (Exception e) {
                runOnUiThread(() -> {
                    showLoading(false);
                    Toast.makeText(ForgotPasswordActivity.this, 
                        "验证失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }
        });
    }

    private void verifyCode() {
        String code = etVerificationCode.getText().toString().trim();
        
        // 验证输入
        if (code.isEmpty()) {
            etVerificationCode.setError("请输入验证码");
            etVerificationCode.requestFocus();
            return;
        }
        
        // 显示加载状态
        showLoading(true);
        
        // 验证验证码
        new android.os.Handler().postDelayed(() -> {
            boolean isValid = emailService.verifyCode(verifiedEmail, code);
            
            showLoading(false);
            
            if (isValid) {
                Toast.makeText(ForgotPasswordActivity.this, "验证码正确", Toast.LENGTH_SHORT).show();
                
                // 更新UI进入下一步
                currentStep = ResetStep.PASSWORD_RESET;
                updateUIForCurrentStep();
            } else {
                etVerificationCode.setText("");
                etVerificationCode.setError("验证码错误或已过期，请重新获取");
                etVerificationCode.requestFocus();
            }
        }, 500);
    }

    private void resetPassword() {
        String newPassword = etNewPassword.getText().toString().trim();
        String confirmPassword = etConfirmPassword.getText().toString().trim();
        
        // 验证输入
        if (newPassword.isEmpty()) {
            etNewPassword.setError("请输入新密码");
            etNewPassword.requestFocus();
            return;
        }
        
        if (newPassword.length() < 6) {
            etNewPassword.setError("密码长度不能小于6位");
            etNewPassword.requestFocus();
            return;
        }
        
        if (!newPassword.equals(confirmPassword)) {
            etConfirmPassword.setError("两次输入的密码不一致");
            etConfirmPassword.requestFocus();
            return;
        }
        
        // 显示加载状态
        showLoading(true);
        
        // 执行密码重置
        executorService.execute(() -> {
            try {
                User user = database.userDao().getUserByUsernameSync(verifiedUsername);
                if (user != null) {
                    user.setPassword(newPassword);
                    database.userDao().updateUser(user);
                    
                    // 发送密码重置成功通知邮件
                    emailService.sendPasswordResetNotification(verifiedEmail, verifiedUsername, 
                        new EmailService.EmailCallback() {
                            @Override
                            public void onSuccess(String result) {
                                // 邮件发送成功或失败都显示重置成功
                                runOnUiThread(() -> {
                                    showLoading(false);
                                    showResetSuccessDialog();
                                });
                            }
                            
                            @Override
                            public void onError(String error) {
                                // 即使邮件发送失败，密码重置仍然成功
                                runOnUiThread(() -> {
                                    showLoading(false);
                                    showResetSuccessDialog();
                                });
                            }
                        });
                } else {
                    runOnUiThread(() -> {
                        showLoading(false);
                        Toast.makeText(ForgotPasswordActivity.this, "用户不存在", Toast.LENGTH_SHORT).show();
                    });
                }
            } catch (Exception e) {
                runOnUiThread(() -> {
                    showLoading(false);
                    Toast.makeText(ForgotPasswordActivity.this, 
                        "密码重置失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }
        });
    }

    private void showResetSuccessDialog() {
        new AlertDialog.Builder(this)
                .setTitle("密码重置成功")
                .setMessage("您的密码已成功重置（模拟），请使用新密码登录")
                .setPositiveButton("返回登录", (dialog, which) -> {
                    finish();
                })
                .setCancelable(false)
                .show();
    }

    /**
     * 显示/隐藏加载状态
     */
    private void showLoading(boolean isLoading) {
        if (isLoading) {
            progressBar.setVisibility(View.VISIBLE);
            btnSendEmail.setEnabled(false);
            btnVerifyCode.setEnabled(false);
            btnResetPassword.setEnabled(false);
        } else {
            progressBar.setVisibility(View.GONE);
            btnSendEmail.setEnabled(true);
            btnVerifyCode.setEnabled(true);
            btnResetPassword.setEnabled(true);
        }
    }
} 